package com.longnuoqi.mydoctor.activity;

import android.content.Context;
import android.content.Intent;
import android.content.SharedPreferences;
import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;
import android.util.Log;
import android.view.KeyEvent;
import android.view.View;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.RelativeLayout;
import android.widget.TextView;
import android.widget.Toast;

import com.android.volley.Request;
import com.android.volley.RequestQueue;
import com.android.volley.Response;
import com.android.volley.VolleyError;
import com.android.volley.toolbox.StringRequest;
import com.android.volley.toolbox.Volley;
import com.longnuoqi.mydoctor.utils.ActivityCollection;
import com.longnuoqi.mydoctor.utils.EncodeDecodeUtil;
import com.yunhe.mydoctor.R;


import org.json.JSONException;
import org.json.JSONObject;

import java.util.Timer;
import java.util.TimerTask;

/**
 * Created by Lenovo on 2015/12/28.
 */
public class UserLandActivity extends AppCompatActivity {
    public static final String CLIENT_ID = "514570";
    public static final String CLIENT_SECRET = "c82919d597b3ce6a5490459ab181ded8";
    private ImageView back;
    private EditText account;
    private EditText password;
    private String accountValue;
    private String passwordValue;
    private TextView forget;
    private TextView regist;
    private RelativeLayout land;

    private String url;

    private static boolean isExit = false;//判断是否退出
    private static boolean hasTask = false;//判断是否是任务
    private Timer timer = new Timer();//声明timer对象，计时器
    private TimerTask timerTask = new TimerTask() {//为timer安排一次执行或重复执行的任务
        @Override
        public void run() {
            isExit = false;
        }
    };

    /*双击退出程序*/
    @Override
    public boolean onKeyDown(int keyCode, KeyEvent event) {
        if (keyCode == KeyEvent.KEYCODE_BACK && event.getAction() == KeyEvent.ACTION_DOWN) {
            if (!isExit) {
                isExit = true;
                Toast.makeText(UserLandActivity.this, "再按一次退出程序", Toast.LENGTH_SHORT).show();
                if (!hasTask) {
                    timer.schedule(timerTask, 2000);//安排在指定延迟后执行指定的任务
                }
            } else {
                ActivityCollection.finishAll();
                //回收资源
                System.exit(0);
            }
            return false;
        }
        return super.onKeyDown(keyCode, event);
    }

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.user_land_layout);
        ActivityCollection.addActivity(this);
        initview();
    }

    private void initview() {
        back = (ImageView) findViewById(R.id.user_land_back_btn);
        account = (EditText) findViewById(R.id.user_land_account_text);
        password = (EditText) findViewById(R.id.user_land_pwd_text);
        forget = (TextView) findViewById(R.id.user_land_forget);
        regist = (TextView) findViewById(R.id.user_land_regist_btn);
        land = (RelativeLayout) findViewById(R.id.user_land_btn);

        back.setOnClickListener(onClickListener);
        forget.setOnClickListener(onClickListener);
        regist.setOnClickListener(onClickListener);
        land.setOnClickListener(onClickListener);
    }

    private View.OnClickListener onClickListener = new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            switch (v.getId()) {
                case R.id.user_land_back_btn:
                    Intent intent = getIntent();
                    setResult(RESULT_OK, intent);
                    finish();
                    break;
                case R.id.user_land_forget:
                    Toast.makeText(UserLandActivity.this, "forget password", Toast.LENGTH_SHORT).show();
                    break;
                case R.id.user_land_regist_btn:
                    Intent land = new Intent(UserLandActivity.this, UserRegistActivity.class);
                    startActivityForResult(land, 0);
                    break;
                case R.id.user_land_btn:
                    accountValue = account.getText().toString().trim();
                    passwordValue = password.getText().toString().trim();
                    userLand();
                    break;
                default:
                    break;
            }
        }
    };

    private void userLand() {
        url = "http://www.tngou.net/api/oauth2/login" + "?client_id=" + CLIENT_ID + "&client_secret=" +
                CLIENT_SECRET + "&name=" + EncodeDecodeUtil.encoderUtf8(accountValue) + "&password=" + passwordValue;
        Log.e("登录地址", url);
        RequestQueue requestQueue = Volley.newRequestQueue(this);
        StringRequest stringRequest = new StringRequest(Request.Method.GET, url, new Response.Listener<String>() {
            @Override
            public void onResponse(String s) {
                Log.e("登录返回数据==", s);
                try {
                    JSONObject jsonObject = new JSONObject(s);
                    boolean status = jsonObject.getBoolean("status");
                    if (status) {
                        String access_token = jsonObject.getString("access_token");
                        String refresh_token = jsonObject.getString("refresh_token");
                        int id = jsonObject.getInt("id");
                        storeSharedPreferences(access_token, refresh_token, id);
                        Intent intent = getIntent();
                        setResult(1, intent);
                        finish();
                    } else {
                        String message = jsonObject.getString("msg");
                        Toast.makeText(UserLandActivity.this, message, Toast.LENGTH_SHORT).show();
                        account.setText("");
                        password.setText("");
                        account.requestFocus();
                    }
                } catch (JSONException e) {
                    e.printStackTrace();
                }
            }
        }, new Response.ErrorListener() {
            @Override
            public void onErrorResponse(VolleyError volleyError) {
                Log.e("ErrorListener==", volleyError + "");

            }
        });
        requestQueue.add(stringRequest);
    }

    public void storeSharedPreferences(String access_token, String refresh_token, int id) {
        SharedPreferences sharedPreferences = getSharedPreferences("userlogin", Context.MODE_PRIVATE);
        SharedPreferences.Editor editor = sharedPreferences.edit();
        editor.putString("access_token", access_token);
        editor.putString("refresh_token", refresh_token);
        editor.putString("account", accountValue);
        editor.putString("password", passwordValue);
        editor.putBoolean("islogin", true);
        editor.putInt("id", id);
        editor.commit();
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        switch (resultCode) {
            case 1:
                String name = data.getStringExtra("account");
                account.setText(EncodeDecodeUtil.decoderUtf8(name));
                password.requestFocus();
                Toast.makeText(UserLandActivity.this, "注册成功！", Toast.LENGTH_SHORT).show();
                break;
            default:
                break;
        }
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        ActivityCollection.removeActivity(this);
    }
}
